package com.huluobo.a2110mvpimdemo.conversation;


import android.util.Log;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;


import com.huluobo.a2110mvpimdemo.R;
import com.huluobo.a2110mvpimdemo.adapter.ConversationAdapter;
import com.huluobo.a2110mvpimdemo.base.BaseFragment;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;

import java.util.ArrayList;
import java.util.List;

public class MyConversationFragment extends
        BaseFragment<ConversationContract.View, ConversationPresenter> implements ConversationContract.View {
    private RecyclerView recyclerView;
    private ConversationAdapter conversationAdapter;
    private List<EMConversation> conversations = new ArrayList<>();
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected int bindLayoutId() {
        return R.layout.fragment_my_conversation;
    }

    @Override
    protected void initData() {
        presenter = new ConversationPresenter();
    }

    @Override
    public void loadData() {
        super.loadData();
        presenter.loadConversations();
    }

    @Override
    protected void initView() {
        recyclerView = findViewById(R.id.conversation_rv);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        conversationAdapter = new ConversationAdapter(conversations, getContext());
        recyclerView.setAdapter(conversationAdapter);
        swipeRefreshLayout = findViewById(R.id.conversation_sr);
        swipeRefreshLayout.setOnRefreshListener(() -> {
            presenter.loadConversations();
        });

        //添加消息监听器,用于接收到消息的时候刷新适配器或者重新读取消息列表
        EMClient.getInstance().chatManager().addMessageListener(messages -> {
            Log.i("TagA", "接收到新消息");
            presenter.loadConversations();
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        presenter.loadConversations();
    }

    @Override
    public void onLoadConversationsSuccess(List<EMConversation> conversations) {
        getActivity().runOnUiThread(() -> {
            if (swipeRefreshLayout.isRefreshing()) {
                swipeRefreshLayout.setRefreshing(false);
            }
            this.conversations.clear();
            this.conversations.addAll(conversations);
            conversationAdapter.notifyDataSetChanged();
        });

    }

    @Override
    public void onLoadConversationsFailed(String error) {
        swipeRefreshLayout.setRefreshing(false);
        Log.i("TagA", "会话列表错误:" + error);
    }
}